<template>
	<view class="question-list-detail">
		<u-tag :text="state.countdown + ' s'" class="timer-btn" shape="circle" type="primary" mode="light"></u-tag>
		<view style="width:100%; text-align: center; margin-bottom: 10px;">{{page}}/{{totalPage}}</view>
		<view class="flex-1">
			<view class="question-list">
				<view
					class="word-item ld"
					:class="{
						change: item.change === true,
						right: item.right === 1,
						error: item.right === 0,
						'ld-jump-out': item.right === 1
					}"
					:style="item.type=='word'?'background-color:#0f6ab1':'background-color:#f0ad4e'"
					:key="item.key"
					v-for="item in pageItems"
					@click="handleChange(item)"
				>{{item.text}}</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, nextTick, watch, computed } from 'vue';
	import { IWord } from '@/store/study';
	import { getUuid, randomArray } from '@/utils';
	import { useTimer, useSoundEffect } from '@/common/hooks';

	/** 组件参数类型 */
	type IProps = {
		wordList : IWord[]
	}

	/** 单词消消乐 */
	defineOptions({ name: 'pairing-elimination', inheritAttrs: false, options: { virtualHost: true } });
	 
	
	// 声明组件基本要素
	const props = withDefaults(defineProps<IProps>(), { wordList: () => [] })
	const { state, startDownTime, clearTimer } = useTimer();
	const { playMp3 } = useSoundEffect();

	// 题目列表
	const questionList = ref<any[]>([]);
	// 对比选项
	const changeItems = ref({ a: null, b: null })
	const page = ref(1);
	const totalPage = ref(1);
	const pageItems = computed(() => {
		var result = questionList.value.filter(x => {
			return x.page == page.value
		})
		return result;
	})

	function initQuestionList() {
		// console.log("initQuestionList",props.wordList);  
		//const tempQuestionList: any[] = [];
		totalPage.value = (props.wordList.length >= 10 ? 2 : 1);

		var leftList = [];
		var rightList = [];
		props.wordList.forEach((item, index, arr) => {
			//console.log(index); 
			var setP = (index < arr.length / 2 ? 1 : 2);
			if (arr.length <= 10) {
				setP = 1;
			}
			//setP = (index<2?1:2);
			leftList.push({
				ID: item.ID,
				text: item.Word,
				type: "word",
				mp3: item.MP3,
				change: false,
				right: null,
				key: getUuid(),
				page: setP
			});
			rightList.push({
				ID: item.ID,
				text: item.Mean,
				type: "mean",
				mp3: item.MP3,
				change: false,
				right: null,
				key: getUuid(),
				page: setP
			});
		})

		questionList.value = [];

		randomArray(leftList);
		randomArray(rightList);

		var currentLeftPageItems = leftList.filter(x => {
			return x.page == page.value;
		})
		var currentRightPageItems = rightList.filter(x => {
			return x.page == page.value;
		})
		
		for (var i = 0; i < currentLeftPageItems.length; i++) {
			questionList.value.push(currentLeftPageItems[i]);
			questionList.value.push(currentRightPageItems[i]);
		}
		
		startDownTime(questionList.value.length / 2 * 15, game_over);
	}

	const emit = defineEmits(['gameover','sendProcess']);

	function game_over() {
		emit('gameover');
	}

	let lastItemA = null;
	let lastItemB = null;
	let lastRight = false;
	function changeQuestion(item : any) {
		// 防止清空后又立马点击
		if (lastItemA && lastItemB) {
			if (lastRight !== false) {
				if(!changeItems.value.a && !changeItems.value.b){
					if(lastItemA.ID === item.ID || lastItemB.ID === item.ID) {
						return;
					}
				}
			}
		}
		
		// 判断a是否存在
		if (!changeItems.value.a) {
			changeItems.value.a = item;
			item.change = true;
		}
		// 取消选择
		else if (changeItems.value.a.key === item.key) {
			changeItems.value.a = null;
			item.change = false;
		}
		// 判断b是否存在
		else if (!changeItems.value.b) {
			changeItems.value.b = item;
			item.change = true;
		}
		// 取消选择
		else if (changeItems.value.b.key === item.key) {
			changeItems.value.b = null;
			item.change = false;
		}
		
		// 配对校验
		if (changeItems.value.a && changeItems.value.b) {
			changeItems.value.a.change = false;
			changeItems.value.b.change = false;
			lastItemA = changeItems.value.a;
			lastItemB = changeItems.value.b;

			// 做对了
			if (changeItems.value.a.ID === changeItems.value.b.ID) {
				lastRight = null;
				changeItems.value.a.right = 1;
				changeItems.value.b.right = 1;
				var row = props.wordList.filter(x => {
					return x.ID == changeItems.value.a.ID;
				})[0];
				if (typeof (row["errorCount"]) == 'undefined') {
					row["errorCount"] = 0;
				}
				playMp3('https://nx5.abc5g.com/res/amazing.mp3?v=1');

				changeItems.value.a = null;
				changeItems.value.b = null;
				console.log('sendProcess');
				emit('sendProcess');

			} else { // 做错了
				lastRight = false;
				changeItems.value.a.right = 0;
				changeItems.value.b.right = 0;
				playMp3('https://nx5.abc5g.com/res/cuowu.mp3?v=2');
				var rowA = props.wordList.filter(x => {
					return x.ID == changeItems.value.a.ID;
				})[0];
				var rowB = props.wordList.filter(x => {
					return x.ID == changeItems.value.b.ID;
				})[0];
				if (typeof (rowA["errorCount"]) == 'undefined') {
					rowA["errorCount"] = 0;
				}
				if (typeof (rowB["errorCount"]) == 'undefined') {
					rowB["errorCount"] = 0;
				}
				rowA["errorCount"] += 1;
				rowB["errorCount"] += 1;

				const tempA = changeItems.value.a;
				const tempB = changeItems.value.b; 
				tempA.right = null;
				tempB.right = null; 
				changeItems.value.a = null;
				changeItems.value.b = null;
			}
		}
		nextPage();
	}

	function nextPage() {
		var temp = questionList.value.filter(x => {
			return x.page == page.value
		})
		//console.log("nextPage",temp)
		var next = true;
		for (var i = 0; i < temp.length; i++) {
			if (temp[i]["right"] == null) {
				next = false;
				break;
			}
		}
		//console.log("next",next);
		if (next) {
			page.value++;
			initQuestionList();
		}
		//console.log("page.value",page.value);
		if (page.value > totalPage.value) {
			game_over();
		}
	}

	function handleChange(item : any) {
		if (item.type == 'word') {
			playMp3(item.mp3);
		}
		if (changeItems.value.a && changeItems.value.b) {
			const isA = changeItems.value.a.key === item.key;
			const isB = changeItems.value.b.key === item.key;

			if (!isA && !isB) {
				changeItems.value.a.right = null;
				changeItems.value.b.right = null;

				nextTick().then(() => {
					changeItems.value.a = null;
					changeItems.value.b = null;
					changeQuestion(item);
				})
				return;
			}
		}

		changeQuestion(item);
	}

	initQuestionList();

	watch(
		() => questionList.value,
		(nVal : any[]) => {
			if (nVal.every(item => item.right)) {
				// 做完了，触发一些事件
				// handleNext() 
				game_over();
			}
		},
		{ deep: true }
	);
</script>

<style lang="scss">
	@import url("@/components/transition-min/transition.min.css");

	.question-list-detail {
		margin: 0 auto;
		position: relative;
		display: flex;
		flex-flow: column;
		flex: 1;
	}

	.timer-btn {
		position: absolute;
		right: 0;
		top: -10px;
		z-index: 8;
	}

	.question-list {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 10px;
	}

	.word-item {
		border: none;
		color: #fff;
		border-radius: 5px;
		height: 50px;
		min-width: 140rpx;
		padding: 5px;
		text-align: center;
		line-height: 40px;
		overflow: hidden;
		font-size: 16px;
	}

	.word-item.change {
		background-color: #FFD800 !important;
	}

	.word-item.right {
		background-color: #22AC38;
		color: #fff;
	}

	.word-item.error {
		background-color: #F02020;
		color: #fff;
	}
</style>